/**
 * Phlame Engine Clientside Core
 * JS codingstyle: Crockford's Patterns (OOP JS)
 */


(function($) {
var Action = function(view, params) {
    params = params || [];
    return {
        "view": view,
        "params": params
    }
};

var Modules = {}; // registry
var Module = function(id) {
    if (!Modules[id]) {
        throw new Error('Module does not exist!');
    }
    var that = Modules[id]; // "create" "this" / load the object data into "that"
    
    return {
        bindTo : function(data, tpl, callback) {
            var tplid = tpl || that.tpl;
            $tpl(tplid).bindTo(data, that.id, that.lang || null, callback);
            return this;
        },
        eval : function(script) {
            eval(script); // @todo error handling
        }
    };
}
Module.create = function(id, obj) {
    if (Modules[id]) {
        throw new Error('Module already exists!');
    }
    Modules[id] = obj;
}

var Response = function(data) {
    // data = {"modul":modulid, "tpl":tplid, "data": data_to_parse}
    data = eval('('+data+')');
    function refresh(modulid, tplid, data, script)
    {
        
    }
};

var request = function(data, callback) {
    this.url = 'AjaxController.php';
    $.post(this.url, data, callback);
}

var Actions = [];
var d = new Date;
var lastRequestTimestamp = d.getTime();
var Timeout;
var Controller = function(view, params){
    this.interval = 2 * 60 * 1000;
    //var args = Array.prototype.slice.apply(arguments);
    var currentTimestamp = new Date.getTime();
    var cActions = Actions;
    
    function setTimeout(){
        window.clearTimeout(Timeout);
        Timeout = window.setTimeout("Controller()", this.interval);
    }
    if (view) {
        cActions.push(Action(view, params));
    }
    if (cActions.length >= 1) {
        request({
            'actions[]': cActions
        }, Response);
    }
    setTimeout();
}
var KeepUpToDate = function(Action) {
    Actions.push(Action);
};

KeepUpToDate.getActions = function() {
    Limiter.resetCountdown();
    return actions;
};

var Limiter = function() {
    
};




// = window.Controller
// = window.Action
// = window.KeepUpToDate
})(jQuery);


//(function($) {
//})(jQuery);


(function($) {
var cache = {}; // static (common) variable of getLang objects
var dir = 'lang/'+'de/';
/**
 * Language cache and getter
 * @param string area selector
 * @param function callback executed after the first intern get
 */
var getLang = window.getLang = function(area, callback) {
    var cbget = callback;
    
    // intern get function loading either from cache or per ajax request, therefor a callback is needed
    function get(area, callback){
        if (cache[area] != undefined) {
            callback(cache[area]);
            cbget && cbget();
            cbget = null;
            return true;
        }
        $.getJSON(getLang.dir + area + '.mo', function(data){
            cache[area] = data;
            callback(cache[area]);
            cbget && cbget();
            cbget = null;
        });
        return false;
    }
    
    return {
        /**
         * replace language variables in a template
         * @param string tpl full Template
         * @param function callback executed with the changed template
         */
        replace: function(tpl, callback){ // extern replace function: execute intern get and chain intern replace into its callback
            get(area, function(lang) { // intern replace function, parsing language variables into templates
                tpl = tpl.replace(/{L_([^{}]*)}/g, function(i, r){
                    return typeof lang[r] === 'string' ? lang[r] : i;
                });
                callback(tpl);
            });
            return this;
        }
    }
}
getLang.dir = dir;
})(jQuery);

(function($, getLang) {
var registry = {}; // static (common) cache of all Template objects
var dir = 'tpl/'; // standard tpl location - access via Template.dir
/**
 * Template cache, getter and parser
 * @param string id
 * @param function callback executed after the first intern get
 */
var Template = $tpl = window.Template = window.$tpl = function (id, callback) { 
    var cbget = callback,
        getrunning = false,
        waiting = [];
    
    // intern get function loading either from cache or per ajax request, therefor a callback is needed
    function get(gid, callback) {
        //console.log('call: get() id:'+gid+' reg:'+registry[gid]);
        if (getrunning) { // prevent and chain simulanuos get requests (e.g. used for extend)
            waiting.push(function() {
                get(gid, callback);
            });
            return -1;
        }
        if (registry[gid]) { // use cache
            callback && callback(registry[gid]);
            var w = waiting.shift();
            w && w();
            cbget && cbget();
            cbget = null;
            return 1;
        }
        getrunning = true;
        $.get(Template.dir + gid + '.tpl', function(data) {
            registry[gid] = data;
            getrunning = false;
            callback && callback(registry[gid]);
            var w = waiting.shift();
            w && w();
            cbget && cbget();
            cbget = null;
        });
        return 0;
        //throw '$tpl(registry): element not found';
    }
    
    return {
        extend : function(withId, placeholder, callback) {
            //console.log('call: extend:'+withId);
            if (!placeholder) {
                placeholder = '{html}';
            }
            get(id, function( ){
                get(withId, function(){
                    registry[withId] = registry[id].replace(placeholder, registry[withId]);
                    callback && callback();
                    id = withId; // change current tpl to the extended one.
                    return true;
                });
            });
            return this; // chain
        },
        bindTo : function(data, appendTo, lang, callback, params) {
            //console.log('call: bindTo');
            var params = params || {};
            params.onBound = callback;
            get(id, function() {
                //console.log('call: innerBindTo');
                if (lang) {
                   var append = appendTo;
                   var node = $(registry[id]).bindTo(data, params);
                    getLang(lang).replace(node, function(tpl){
                        $(tpl).appendTo(append);
                        callback && callback();
                    });
                    return true;
                }
                $(registry[id]).bindTo(data, params);
                return false;
            });
            return this; // chain
        }
    };
};
Template.dir = dir;
Template.set = function (id, tpl) {
    registry[id] = tpl;
};

/*
$tpl.dir = 'tpl/ajax/';

$tpl.extend = function(which, id, callback, placeholder) {
    if (placeholder == undefined) {
        placeholder = '{html}';
    }
    if (callback == undefined) {
        callback = function(){}
    }
    $tpl.get(which, function(tpl) {
        $tpl.get(id, function(ext) {
            ext = tpl.replace(placeholder, ext);
            $tpl._set(id, ext);
            callback(ext);
        });
    });
}
$tpl.bindTo = function(id, data, params, callback) {
    if (callback == undefined) {
        callback = function(){}
    }
    $tpl.get(id, function(tpl) {
        if (params.lang != undefined) {
            getLang(params.lang, function(lng) {
                tpl = getLang.replace(tpl, lng);
                $(tpl).bindTo(data, params);
                callback();
            });
            return true;
        }
        $(tpl).bindTo(data, params);
        callback();
        return false;
    });
}
*/
})(jQuery, getLang);

